import type { AxiosRequestConfig } from "axios";
import axios from "axios";

import { useUserStore } from "@/stores/user";

function createInstance(config: AxiosRequestConfig = {}) {
	const instance = axios.create({
		timeout: 50000,
		headers: {
			"Content-Type": "application/json",
		},
		maxRedirects: 0,
		...config,
	});
	instance.interceptors.request.use((config) => {
		const { authorization } = useUserStore();
		config.headers!.Authorization = authorization;
		return config;
	});
	instance.interceptors.response.use(
		(response) => {
			const userStore = useUserStore();

			const code = +response.data?.code;
			if (code) {
				if ([4001, 4002, 4003, 4004, 4005].includes(code)) {
					userStore.logout();
					// const userStore = useUserStore();
					// userStore.cleanLogin();
				}

				if (code >= 400) {
					console.error(response);
					const message = response?.data?.message || "请求异常";
					ElMessage.error(message);
					return Promise.reject(response);
				}
			}
			return response;
		},
		(error = {}) => {
			const message = error.response?.data?.message || "请求异常";
			ElMessage.error(message);
			return Promise.reject(error);
		},
	);
	return instance;
}

const instance = createInstance();

export async function whRequest<T>(
	options: AxiosRequestConfig<T> & Record<string, any>,
) {
	const { path = {}, ...params } = options;
	let url = options.url;
	for (const key in path) {
		url = url?.replaceAll(`{${key}}`, path[key]);
	}
	const { data } = await instance.request({
		baseURL: import.meta.env.VITE_SERVER_URL,
		...params,
		url,
	});
	return data;
}
